<template>
<div>
  <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
    <el-breadcrumb-item :to="{ path: '/' }">
      <i class="el-icon-s-promotion"></i>后台管理
    </el-breadcrumb-item>
    <el-breadcrumb-item :to="{ path: '/permission/admin' }">管理员管理</el-breadcrumb-item>
    <el-breadcrumb-item><a href="/">添加管理员</a></el-breadcrumb-item>
  </el-breadcrumb>
  <el-divider></el-divider>
  <div>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <div style="width: 30%;">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="ruleForm.username"></el-input>
    </el-form-item>
    </div>
    <div style="width: 30%;">
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password"></el-input>
    </el-form-item>
    </div>
    <div style="width: 20%;">
    <el-form-item label="年龄" prop="age">
      <el-input v-model="ruleForm.age"></el-input>
    </el-form-item>
    </div>
    <el-form-item label="头像" prop="avatar">
      <el-upload
          class="avatar-uploader"
          action="http://localhost:9202/resources/upload/image/product"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
        <img v-if="ruleForm.avatar" :src="ruleForm.avatar" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
  </el-form-item>
    <div style="width: 30%;">
    <el-form-item label="性别" prop="gender">
      <el-radio v-model="ruleForm.gender" label="男">男</el-radio>
      <el-radio v-model="ruleForm.gender" label="女">女</el-radio>
    </el-form-item>
    </div>
    <div style="width: 30%;">
    <el-form-item label="手机号码" prop="phoneNumber">
      <el-input v-model="ruleForm.phoneNumber"></el-input>
    </el-form-item>
    </div>
    <div style="width: 30%;">
    <el-form-item label="身份证号" prop="idCard">
      <el-input v-model="ruleForm.idCard"></el-input>
    </el-form-item>
    </div>
    <div style="width: 50%;">
    <el-form-item label="地址" prop="address">
      <el-input v-model="ruleForm.address"></el-input>
    </el-form-item>
    </div>
    <div style="width: 70%;">
    <el-form-item label="简介" prop="description">
      <el-input v-model="ruleForm.description"></el-input>
    </el-form-item>
    </div>
    <el-form-item label="是否启用" prop="enable">
      <el-switch
          v-model="ruleForm.enable"
          :active-value="1"
          :inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ccc">
      </el-switch>
    </el-form-item>
    <el-form-item label="角色" prop="roleIds">
      <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择">
        <el-option
            v-for="item in roleListOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">添加</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
      <el-button type="warning" @click="$router.push('/permission/admin')">返回列表</el-button>
    </el-form-item>
  </el-form>
  </div>
</div>
</template>

<script>
export default {
  data() {
    return {
      roleListOptions: [],
      ruleForm: {
        username: '测试数据001',
        password:'123456',
        gender:"1",
        age:'18',
        avatar:'https://img2.baidu.com/it/u=4244269751,4000533845&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
        phoneNumber:'13700137001',
        idCard:'13700137001',
        description:'测试数据的简介001',
        address:"",
        enable:1,
        roleIds:[],

      },
      rules: {
        username: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        age: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
          {pattern: /^(1[8-9]|[2-5]\d|99)$/,message: '请输入正确年龄',trigger: 'blur'}
        ],
        nickname: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        avatar: [
          {required: true, message: '请选择头像', trigger: 'blur'}
        ],
        phoneNumber: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {len: 11,message: '电话号码格式错误',trigger: 'blur'}
        ],
        idCard: [
          {required: true, message: '请输入身份证号', trigger: 'blur'},
          {pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
          message: '身份证格式错误',trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入简介', trigger: 'blur'},
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'blur'},
        ],
        enable: [],
        roleIds: [
          {required: true, message: '请选择角色', trigger: 'blur'},
        ]
      }
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.ruleForm.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:9201/admin/add-new';
          console.log('url = ' + url);

          // let  formData = 'name=' + this.ruleForm.name
          //       + '&description=' + this.ruleForm.description
          //       + '&sort=' + this.ruleForm.sort;

          let formData = this.qs.stringify(this.ruleForm);

          console.log("formData=" + formData)
          let localJwt = localStorage.getItem('localJwt');


          this.axios
              .create({
                'headers': {
                  'Authorization':localJwt
                }
              })
              .post(url,formData).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state==20000){
              this.$message({
                message: '添加管理员成功',
                type: 'success'
              });
              this.resetForm(formName);
            } else {
              this.$alert(jsonResult.message, '错误', {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }

          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    loadRoleList() {
      let url = 'http://localhost:9201/role/list?query=all';
      console.log('url = ' + url);


      this.axios.get(url).then((response) => {
        let jsonResult = response.data;
        console.log(jsonResult);
        if (jsonResult.state == 20000) {
          this.roleListOptions = jsonResult.data.list;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    }
  },
  mounted(){
    this.loadRoleList();
  }
}
</script>

<style scoped>

</style>